#include "public.h"

int newsfd[100], i = 0;

void *func(void *q)
{
	char cbuf[100];
	char sbuf[100];
	char name[100];
	int index = *((int *)q);
	read(newsfd[index], name, sizeof(name));
	sprintf(sbuf, "热烈欢迎 %s 进入本聊天室！！\n", name);
	printf("sfd=%d\n", newsfd[index]);
	printf("name=%s\n", name);
	int i;
	for (i = 0; i < 100; i++)
	{
		write(newsfd[i], sbuf, sizeof(sbuf));
	}
	while (1)
	{
		read(newsfd[index], cbuf, sizeof(cbuf));
		if (strcmp(cbuf, "quit") == 0)
		{
			sprintf(sbuf, "%s已经退出聊天室", name);
			int i;
			for (i = 0; i < 100; i++)
			{
				write(newsfd[i], sbuf, sizeof(sbuf));
			}
			newsfd[index] = -1;
			break;
		}
		sprintf(sbuf, "%s:%s", name, cbuf);
		int i;
		for (i = 0; i < 100; i++)
		{
			write(newsfd[i], sbuf, sizeof(sbuf));
		}
	}
}

int main()
{
	int sd = socket(AF_INET, SOCK_STREAM, 0);
	if (sd == -1)
	{
		perror("socket failed!\n");
		exit(-1);
	}
	struct sockaddr_in addr;
	struct sockaddr_in clientaddr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(1025);
	inet_aton("127.0.0.1", &addr.sin_addr);
	int ss = bind(sd, (struct sockaddr *)&addr, sizeof(addr));
	if (ss == -1)
	{
		perror("bind failed!\n");
		exit(-1);
	}
	if (listen(sd, 100) == -1)
	{
		perror("listen failed!\n");
		exit(-1);
	}
	int len = sizeof(clientaddr);
	int index = 0;
	while (1)
	{
		newsfd[i++] = accept(sd, (struct sockaddr *)&clientaddr, &len);
		index = i - 1;
		if (newsfd[index] == -1)
		{
			perror("accept failed\n");
			exit(-1);
		}
		pthread_t tid;
		pthread_create(&tid, NULL, func, &index);
	}
}